package biblioteca.frm;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;

import biblioteca.modelos.Usuario;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class FrmLogin extends JFrame {

	private JPanel contentPane;
	private JTextField textFieldUser;
	private JTextField textFieldPassword;

	/**
	 * Launch the application.
	 */
	public void iniciaTela() {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public FrmLogin() {
		iniciaTela();
		setTitle("Login");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 314, 186);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JPanel panel = new JPanel();
		panel.setBounds(10, 11, 283, 85);
		contentPane.add(panel);
		panel.setLayout(null);
		
		textFieldUser = new JTextField();
		textFieldUser.setBounds(56, 11, 217, 20);
		panel.add(textFieldUser);
		textFieldUser.setColumns(10);
		
		textFieldPassword = new JTextField();
		textFieldPassword.setColumns(10);
		textFieldPassword.setBounds(56, 42, 217, 20);
		panel.add(textFieldPassword);
		
		JLabel lblUsurio = new JLabel("Usu\u00E1rio:");
		lblUsurio.setBounds(10, 14, 46, 14);
		panel.add(lblUsurio);
		
		JLabel lblSenha = new JLabel("Senha:");
		lblSenha.setBounds(10, 45, 46, 14);
		panel.add(lblSenha);
		
		JButton btnCancelar = new JButton("Cancelar");
		btnCancelar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		btnCancelar.setBounds(168, 107, 89, 23);
		contentPane.add(btnCancelar);
		
		JButton btnLogin = new JButton("Login");
		
		btnLogin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				login();
			}
		});
		btnLogin.setBounds(69, 107, 89, 23);
		contentPane.add(btnLogin);
	}
	
	private void login(){
		if (!(textFieldUser.getText().equals("") && textFieldPassword.getText().equals(""))){
			Usuario usuario = new Usuario("", textFieldUser.getText(), textFieldPassword.getText());
			if (usuario.login()){
				new FrmMenu();
				dispose();
			}
			else{
				JOptionPane.showMessageDialog(null, "Usuario e/ou senha invalido!!!");
				textFieldUser.setText("");
				textFieldPassword.setText("");
			}
		}
	}
}
